package cn.com.fattiger.framework.cms.admin.common.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import cn.com.fattiger.framework.cms.config.CustomConfig;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateNotFoundException;

/**
 * 文件下载控制类
 *
 * @author Administrator
 */
@Controller
public class FileController {

    @Autowired
    private CustomConfig customConfig;

    @Autowired
    private Configuration templateConfiguration;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    static final Logger logger = Logger.getLogger(FileController.class);
    @RequestMapping(value = "filedownload.do", method = RequestMethod.GET)
    public void fileDownload(HttpServletResponse response, String fileName) {

        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + fileName);
        ServletOutputStream out;
        File file = new File(customConfig.getUploadRoot_cms() + fileName);
        logger.info(file+"文件");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            out = response.getOutputStream();


            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = inputStream.read(buffer);
                out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "fileUpload.do", method = RequestMethod.POST)
    @ResponseBody
    public Object fileUpload(HttpServletRequest request, Integer type, String filePath, int replace) {
        Map<String, Object> response = new HashMap<>();
        try {
            MultipartFile uploadFile = ((MultipartHttpServletRequest) request).getFile("uploadFile");
            String fileName = uploadFile.getOriginalFilename();
            String toDir;
            switch (type) {
                case 0:
                    toDir = customConfig.getUploadRoot();
                    break;
                case 1:
                    toDir = customConfig.getTemplateRoot();
                    break;
                case 2:
                    toDir = customConfig.getUploadRoot_image();
                    break;
                case 3:
                    toDir = customConfig.getUploadRoot();
                    break;
                case 4:
                    toDir = filePath;
                    break;
                default:
                    toDir = customConfig.getUploadRoot();
                    break;
            }

            File toDirFile = new File(toDir);
            if (!toDirFile.exists()) {
                toDirFile.mkdirs();
            }

            File toFile = new File(toDir + File.separator + fileName);
            if (replace == 0 && toFile.exists()) {
                response.put("code", 201);
                response.put("message", "file exist.");
                return response;
            }

            uploadFile.transferTo(toFile);
            if (type == 10) {//dynamic template update.
                String templateName = fileName.replaceAll("\\.ftl", "");
                try {
                    freeMarkerConfigurer.getConfiguration().getTemplate(fileName);
                } catch (TemplateNotFoundException e) {
                    System.out.println("template:" + templateName + " not found.");
                    String templateContent = new String(uploadFile.getBytes(), "utf-8");
                    StringTemplateLoader stringLoader = new StringTemplateLoader();
                    stringLoader.putTemplate(templateName, templateContent);
                    freeMarkerConfigurer.getConfiguration().setTemplateLoader(stringLoader);
                }
            }

            response.put("code", 200);
            response.put("message", "success.");
        } catch (Exception e) {
            e.printStackTrace();
            response.put("code", 500);
            response.put("message", e.getMessage());
        }
        return response;
    }
}